package xfile

import (
	"image"
	"image/gif"
	"image/jpeg"
	"image/png"
	"os"

	"gitee.com/xiaoyutab/xgotool/xerror"
	"golang.org/x/image/bmp"
	"golang.org/x/image/tiff"
	"golang.org/x/image/vp8l"
	"golang.org/x/image/webp"
)

// 打开图片文件
func OpenImage(file string) (image.Image, error) {
	if fi, err := os.Stat(file); err != nil {
		return nil, err
	} else if fi.IsDir() {
		return nil, xerror.New("传入的路径为目录，请调整后再次重试")
	}
	// 打开文件
	f, err := os.Open(file)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	tmp, err := jpeg.Decode(f)
	if err != nil {
		tmp, err = png.Decode(f)
		if err != nil {
			tmp, err = gif.Decode(f)
			if err != nil {
				tmp, err = webp.Decode(f)
				if err != nil {
					tmp, err = bmp.Decode(f)
					if err != nil {
						tmp, err = tiff.Decode(f)
						if err != nil {
							tmp, err = vp8l.Decode(f)
							if err != nil {
								return nil, xerror.New("使用jpeg、png、gif、webp、bmp、tiff、vp8l进行图像解码均失败")
							}
						}
					}
				}
			}
		}
	}
	return tmp, err
}
